package com.h2cloud.JUCTest.reentrantReadWriteLock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Package: com.h2cloud.JUCTest.reentrantReadWriteLock
 * @ClassName: LockDegradeExample
 * @Author: h2cloud
 * @CreateTime: 2024/7/10 11:42 下午
 * @Description:
 */
public class LockDegradeExample {
	private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
	private final ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();
	private final ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();

	public void performLockDegrade() {
		writeLock.lock();
		try {
			// 在写锁保护下进行一些写操作
			System.out.println("Writing...");

			// 降级为读锁
			readLock.lock();
		} finally {
			// 释放写锁
			writeLock.unlock();
		}

		try {
			// 在读锁保护下进行一些读操作
			System.out.println("Reading...");
		} finally {
			// 释放读锁
			readLock.unlock();
		}
	}

	public static void main(String[] args) {
		LockDegradeExample example = new LockDegradeExample();
		example.performLockDegrade();
	}
}
